<template>
  <div class="box">
    <el-card style="margin: 20px">
      <!-- 查询表单 -->
      <el-form :inline="true" class="demo-form-inline">
        <el-row>
          <el-col :span="12">
            <el-form-item label="姓名">
              <el-input
                v-model="searchForm.name"
                placeholder="请输入姓名"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12" style="display: flex">
            <el-button type="primary" size="medium " @click="search"
              >查询</el-button
            >
            <el-button type="primary" size="medium " @click="addUser"
              >新增</el-button
            >
            <el-button type="primary" size="medium " @click="uplodad"
              >下载模板</el-button
            >
            <el-upload
              style="margin-left: 10px"
              class="upload-demo inline-block"
              action="/drug/user/upload"
              multiple
              :on-success="successD"
              :file-list="fileList"
              :show-file-list="false"
            >
              <el-button type="primary" size="medium ">导入数据</el-button>
            </el-upload>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <el-card style="margin: 20px">
      <!-- 表格
        @selection-change="handleSelectionChange"
       -->
      <el-table
        style="width: 100%"
        stripe
        :data="list"
        border
        :header-cell-style="{ background: '#ebeef5' }"
      >
        <el-table-column type="index" label="序号" width="60"></el-table-column>
        <el-table-column
          :prop="item.prop"
          v-for="(item, index) in tableList"
          :key="index"
          :label="item.label"
          :width="item.width"
        >
        </el-table-column>
        <el-table-column label="职务" prop="job" width="100">
          <template slot-scope="{ row }">
            {{ row.job == 1 ? "领导" : "民警" }}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="{ row }">
            <el-button icon="el-icon-edit" type="text" @click="editUser(row)"
              >编辑</el-button
            >
            <el-popconfirm
              :title="`确认删除${row.name}吗？`"
              @confirm="deleteRole(row)"
            >
              <el-button type="text" slot="reference" icon="el-icon-delete"
                >删除</el-button
              >
            </el-popconfirm>
            <el-button
              icon="el-icon-refresh-right"
              type="text"
              @click="resetPassword(row)"
              >重置密码</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 添加与编辑弹窗 -->
      <el-dialog
        :title="title"
        :visible.sync="dialogVisible"
        width="40%"
        :before-close="handleClose"
        @open="open"
      >
        <el-form
          ref="ruleForm"
          label-width="150px"
          :model="formList"
          :rules="rules"
        >
          <el-form-item label="姓名" prop="name">
            <el-input
              v-model="formList.name"
              style="width: 300px"
              size="medium "
              placeholder="请输入姓名"
            ></el-input>
          </el-form-item>
          <el-form-item label="账号" prop="username"
            ><el-input
              :disabled="!edit"
              v-model="formList.username"
              style="width: 300px"
              size="medium "
              placeholder="请输入账号"
            ></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password" v-if="edit"
            ><el-input
              v-model="formList.password"
              style="width: 300px"
              size="medium "
              placeholder="请输入密码"
            ></el-input>
          </el-form-item>
          <el-form-item label="所属大队 " prop="deptId">
            <el-cascader
              placeholder="请选择"
              size="medium"
              style="width: 300px"
              v-model="formList.deptId"
              popper-class="cascaderClass"
              :show-all-levels="false"
              :options="options"
              :props="{
                checkStrictly: true,
                label: 'deptName',
                value: 'id',
                children: 'deptList',
              }"
            ></el-cascader>
          </el-form-item>
          <el-form-item label="职务" prop="job">
            <el-radio v-model="formList.job" :label="1">领导</el-radio>
            <el-radio v-model="formList.job" :label="2">民警</el-radio>
          </el-form-item>
          <el-form-item label="角色" prop="roleIds">
            <el-select
              v-model="formList.roleIds"
              placeholder="请选择"
              multiple
              size="medium"
              style="width: 300px"
            >
              <el-option
                v-for="item in optionsList"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="手机号码" prop="phone"
            ><el-input
              v-model="formList.phone"
              style="width: 300px"
              size="medium "
              placeholder="请输入手机号码"
            ></el-input>
          </el-form-item>
          <el-form-item label="座机" prop="specialPlane"
            ><el-input
              v-model="formList.specialPlane"
              style="width: 300px"
              size="medium "
              placeholder="请输入座机号码"
            ></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirm">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分页器 -->
      <el-pagination
        style="margin-top: 20px; text-align: center"
        :current-page="page"
        :page-size="limit"
        :page-sizes="[8, 10, 15]"
        @current-change="getList"
        @size-change="handleSizeChange"
        layout="prev, pager, next,jumper,->,total,sizes "
        :total="total"
      >
      </el-pagination>
    </el-card>
  </div>
</template>

<script>
import crypto from "@/utils/crypto";
export default {
  name: "",
  data() {
    return {
      fileList: [],
      // 是否修改
      edit: "",
      value: [],
      radio: "1",
      radio1: "1",
      list: [],
      // 表格头数据
      tableList: [
        { prop: "username", label: "登录账号", width: "150" },
        { prop: "name", label: "姓名", width: "150" },
        { prop: "deptName", label: "所属大队", width: "100" },
        { prop: "specialPlane", label: "座机", width: "100" },
        { prop: "phone", label: "手机号", width: "100" },
      ],
      options: [],
      // 页数
      page: 1,
      // 展示数据条数
      limit: 8,
      // 数据条数
      total: 1,
      // 图片路径
      imageUrl: "",
      // 控制弹窗字段
      dialogVisible: false,
      // 弹窗名
      title: "",
      // 查询表单
      searchForm: {
        // 姓名
        name: "",
      },
      // 表单列表
      formList: {
        // 所属机构id不能为空
        deptId: 0,
        // 	职务 1：领导 2：民警
        job: 0,
        // 姓名
        name: "",
        // 密码
        password: "",
        // 手机号码
        phone: "",
        // 座机
        specialPlane: "",
        // 启用状态 1-启用 0-禁用,示例值(1)
        usable: 1,
        // 	账号
        username: "",
        // 角色ids
        roleIds: [],
      },
      // 下拉框列表
      optionsList: [],
      rules: {
        deptId: [
          { required: true, message: "请选择所属大队", trigger: "change" },
        ],
        job: [{ required: true, message: "请选择职务", trigger: "change" }],
        name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        phone: [
          { required: true, message: "请填写手机号", trigger: "blur" },
          { min: 11, max: 11, message: "请输入11位手机号", trigger: "change" },
        ],
        specialPlane: [
          { required: true, message: "请填写座机", trigger: "blur" },
        ],
        username: [{ required: true, message: "请填写账号", trigger: "blur" }],
        roleIds: [{ required: true, message: "请选择角色", trigger: "blur" }],
      },
    };
  },
  mounted() {
    this.getList();
  },
  methods: {
    // 获取列表数据
    async getList(pager = 1) {
      this.page = pager;
      const { page, limit, searchForm } = this;
      let data = {
        name: searchForm.name,
        pageNumber: page,
        pageSize: limit,
        userId: this.sessionData("get", "userId"),
      };
      let result = await this.$API.personnel.reqGetList(data);
      if (result.status == 200) {
        this.list = result.data.records;
        this.total = result.data.total;
      }
    },
    // 每页展示数据数量发生变化时
    handleSizeChange(limit) {
      this.limit = limit;
      this.getList();
    },
    // 新增人员
    addUser() {
      this.title = "新增人员";
      this.edit = true;
      (this.formList = {
        // 所属机构id不能为空
        deptId: 0,
        // 	职务 1：领导 2：民警
        job: 0,
        // 姓名
        name: "",
        // 密码
        password: "",
        // 手机号码
        phone: "",
        // 座机
        specialPlane: "",
        // 启用状态 1-启用 0-禁用,示例值(1)
        usable: 1,
        // 	账号
        username: "",
        // 角色ids
        roleIds: [],
      }),
        (this.dialogVisible = true);
    },
    // 编辑人员
    editUser(row) {
      console.log(row);
      let roles = [];
      row.roles.forEach((item) => {
        roles.push(item.id);
      });
      this.formList = {
        deptId: row.deptId,
        id: row.id,
        job: row.job,
        username: row.username,
        name: row.name,
        phone: row.phone,
        roleIds: roles,
        specialPlane: row.specialPlane,
        usable: row.usable,
      };
      console.log(this.formList);
      this.title = "编辑人员";
      this.edit = false;
      this.dialogVisible = true;
    },
    // 打开弹窗时的回调
    async open() {
      let result = await this.$API.personnel.reqGetRoleList();

      if (result.status == 200) {
        this.optionsList = result.data;
      }
      let res = await this.$API.notificationd.reqGetGroupList();
      if (result.status == 200) {
        this.options = res.data;
      }
    },
    // 关闭弹窗的回调
    handleClose(done) {
      this.$confirm("您还未确认保存，确认退出吗？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },
    // 弹框确认按钮
    confirm() {
      const deptIdArr = this.formList.deptId.toString();
      this.formList.deptId = deptIdArr.substring(
        deptIdArr.lastIndexOf(",") + 1
      );
      if (!this.formList.id) {
        const passWord = crypto.encrypt(this.formList.password);
        this.formList.password = passWord;
      } else {
        this.formList.roleId = this.formList.roleIds;
      }
      console.log(this.formList);
      this.$refs.ruleForm.validate(async (success) => {
        if (success) {
          let result = await this.$API.personnel.reqAddOrEdit(this.formList);
          if (result.status == 200) {
            this.$message({
              message: this.formList.id ? "修改成功" : "新增成功",
              type: "success",
            });
            this.dialogVisible = false;
            this.getList(this.formList.id ? this.page : 1);
          }
        } else {
          return false;
        }
      });
    },
    // 确认删除按钮
    async deleteRole(row) {
      let result = await this.$API.personnel.reqDelete(row.id);
      if (result.status == 200) {
        this.$message({
          message: "删除成功",
          type: "success",
        });
        // 当当前页删完，自动跳到上一页
        this.getList(this.list.length > 1 ? this.page : this.page - 1);
      }
    },
    // 重置密码按钮
    resetPassword(row) {
      this.$confirm(
        "重置密码,该账号可用初始密码登陆初始密码123456",
        "重置密码",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(async () => {
          let result = await this.$API.personnel.reqResetPassword(row.id);
          if (result.status == 200) {
            this.$message({
              type: "success",
              message: "重置成功!",
            });
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消重置",
          });
        });
    },
    // 下载按钮
    uplodad() {
      this.$API.personnel.reqGetExport();
    },
    successD() {
      this.$message({
        message: "上传成功",
        type: "success",
      });
      this.getList();
    },
    // 查询按钮
    search() {
      this.getList();
    },
  },
};
</script>

<style lang="scss" scoped></style>
